﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MusicOnLine.Common;
using System.Web.Mvc;
using System.Xml;
using System.Xml.Linq;
namespace MusicOnLine.Common
{
    public class XDocumentBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string key = bindingContext.ModelName;
            ValueProviderResult vpr = bindingContext.ValueProvider.GetValue(key);
            if (vpr != null && vpr.RawValue != null && !String.IsNullOrEmpty(vpr.AttemptedValue))
            {
                //在模型状态中保存尝试值
                bindingContext.ModelState.SetModelValue(key, vpr);
                string tempString = ((String[])vpr.RawValue)[0];
                XDocument xml = null;
                try
                {
                    xml = XDocument.Parse(tempString);
                }
                catch (XmlException)
                {
                    //无法解析XML文本，则设置模型错误状态
                    bindingContext.ModelState.AddModelError(key, "Not valid XML");
                    return null;
                }
                //如果模型已经存在，则替换
                XDocument existingModel = bindingContext.Model as XDocument;
                if (existingModel != null)
                {
                    if (existingModel.Root != null)
                    {
                        existingModel.Root.ReplaceWith(xml.Root);
                    }
                    else
                    {
                        existingModel.Add(xml.Root);
                    }
                    return existingModel;
                }
                else
                {
                    return xml;
                }
            }
            return null;
        }
    }
}